package wendyeq.iweb.blog.web.controller;

import java.text.SimpleDateFormat;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.TimeZone;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

import org.apache.log4j.Logger;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestHeader;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;

import wendyeq.iweb.blog.pojo.Article;
import wendyeq.iweb.blog.pojo.Comment;
import wendyeq.iweb.blog.pojo.Visitor;
import wendyeq.iweb.blog.service.IArchiveService;
import wendyeq.iweb.blog.service.IArticleService;
import wendyeq.iweb.blog.service.ICategoryService;
import wendyeq.iweb.blog.service.ICommentService;
import wendyeq.iweb.blog.service.ITagsService;
import wendyeq.iweb.blog.service.IVisitorService;
import wendyeq.iweb.blog.util.UserAgentUtil;

@Controller("publicController")
public class PublicController {
	private static final Logger logger = Logger.getLogger(PublicController.class);
	
	@Resource(name="articleServiceImpl")
	private IArticleService articleService;
	
	@Resource(name="categoryServiceImpl")
	private ICategoryService categoryService;
	
	@Resource(name="commentServiceImpl")
	private ICommentService commentService;
	
	@Resource(name="tagsServiceImpl")
	private ITagsService tagsService;
	
	@Resource(name="archiveServiceImpl")
	private IArchiveService archiveService;
	
	@Resource(name="visitorServiceImpl")
	private IVisitorService visitorService;	
	
	public void makeSidebar(HttpServletRequest request , ModelMap model){
		List<Article> articles = this.articleService.findAll();
		Map<String,Integer> archive = new HashMap<String,Integer>();
		
		SimpleDateFormat format = new SimpleDateFormat("yyyy-MM");
		format.setTimeZone(TimeZone.getTimeZone( "GMT+8"));
		for(Article a : articles){
			String data = format.format(a.getCreatedTime());
			if(archive.get(data)==null){
				logger.warn("null--"+data);
				archive.put(data, 1);
			}else{
				logger.warn("have--"+data);
				archive.put(data, archive.get(data)+1);
			}
		}
		model.addAttribute("categorys",this.categoryService.findAll());
		model.addAttribute("comments",this.commentService.findByPage(0, 10));
		model.addAttribute("tags", this.tagsService.findAll());
		model.addAttribute("archives",this.archiveService.findAll());
	}
	
	@RequestMapping("/")
	public String initing(HttpServletRequest request, ModelMap model) {
		int page = 1;
		List<Article> articles = this.articleService.findAll();
		int artSize = articles.size();
		if(artSize<10){
			model.addAttribute("articles",articles );
		}else if(artSize-page*10>=0){
			model.addAttribute("articles",articles.subList((page-1)*10,page*10));
		}else {
			model.addAttribute("articles",articles.subList((page-1)*10,artSize));
		}
		model.addAttribute("artSize", artSize);
		model.addAttribute("page", page);
		model.addAttribute("type", "article");
		makeSidebar(request, model);
		return "index";
	}
	
	@RequestMapping("/admin")
	public String adminInit(HttpServletRequest request, ModelMap model) {
		makeSidebar(request, model);
		return "admin/index";
	}
	
	@RequestMapping("/article/{year}/{month}/{day}/{alias}")
	public String getArticle(@RequestHeader("User-Agent") String userAgent,@PathVariable String year, 
			@PathVariable String month, @PathVariable String day, @PathVariable String alias, 
			HttpServletRequest request, ModelMap model){
		String ip = request.getRemoteAddr();
		String[] os = UserAgentUtil.getOS(userAgent);
		String[] browser = UserAgentUtil.getBrowser(userAgent);
		Visitor visitor = new Visitor(ip, os[os.length-1], browser[os.length-1]);
		visitor.setUserAgent(userAgent);
		this.visitorService.save(visitor);
		//Visitor visitor = this.visitorService.insert(ip, os[os.length-1], browser[browser.length-1], userAgent);
		String date = year+"-"+month+"-"+day;
		//this.articleService.updateByVisitor(this.articleService.findByTitle(title,date), visitor.getKey().toString());
		Article article = this.articleService.findByAlias(alias,date);
		model.addAttribute("article",article);
		makeSidebar(request, model);
		return "article";
	}
	
	@RequestMapping("/article/list/{page}")
	public String listArticle(@PathVariable int page, HttpServletRequest request, ModelMap model) {
		List<Article> articles = this.articleService.findAll();
		int artSize = articles.size();
		if(artSize<10){
			model.addAttribute("articles",articles );
		}else if(artSize-page*10>=0){
			model.addAttribute("articles",articles.subList((page-1)*10,page*10));
		}else {
			model.addAttribute("articles",articles.subList((page-1)*10,artSize));
		}
		model.addAttribute("artSize", artSize);
		model.addAttribute("key", "list");
		model.addAttribute("type", "article");
		model.addAttribute("page", page);
		makeSidebar(request, model);
		return "articleList";
	}
	
	@RequestMapping("/archive/{archive}/{page}")
	public String getArticleByArchive(@PathVariable String archive, @PathVariable int page, HttpServletRequest request, ModelMap model){
		List<Article> articles = this.articleService.findByArchive((page-1)*10,page*10,archive);
		model.addAttribute("articles",articles);
		model.addAttribute("artSize", articles.size());
		model.addAttribute("key", archive);
		model.addAttribute("type", "archive");
		model.addAttribute("page", page);
		makeSidebar(request, model);
		return "articleList";
	}
	
	@RequestMapping("/category/{cat}/{page}")
	public String findArticleByCategory(@PathVariable String cat, @PathVariable int page, HttpServletRequest request, ModelMap model) {
		List<Article> articles = this.articleService.findByCat((page-1)*10,page*10,cat);
		model.addAttribute("articles",articles);
		model.addAttribute("artSize", articles.size());
		model.addAttribute("key", cat);
		model.addAttribute("type", "category");
		model.addAttribute("page", page);
		makeSidebar(request, model);
		return "articleList";
	}
	
	@RequestMapping("/tags/{tag}/{page}")
	public String findArticleByTags(@PathVariable String tag, @PathVariable int page, HttpServletRequest request, ModelMap model){
		List<Article> articles = this.articleService.findByTag((page-1)*10,page*10,tag);
		model.addAttribute("articles",articles);
		model.addAttribute("artSize", articles.size());
		model.addAttribute("key", tag);
		model.addAttribute("type", "tags");
		model.addAttribute("page", page);
		makeSidebar(request, model);
		return "articleList";
	}
	
	@RequestMapping("/comment/post/{aid}")
	public String postComment(@PathVariable String aid, @RequestParam String content, @RequestParam String name,
			@RequestParam String email, @RequestParam String website, @RequestHeader("User-Agent") String userAgent ,
			HttpServletRequest request, ModelMap model){
		String ip = request.getRemoteAddr();
		String[] os = UserAgentUtil.getOS(userAgent);
		String[] browser = UserAgentUtil.getBrowser(userAgent);
		Comment comment = new Comment(this.articleService.findById(aid),name,content);
		comment.setEmail(email);
		comment.setWebsite(website);
		this.commentService.save(comment);
		//comment = this.commentService.insert(aid, content, name, email, website);
		//Visitor visitor = this.visitorService.insert(ip, os[os.length-1], browser[browser.length-1], userAgent, comment);
		//this.commentService.updateByVisitor(comment, visitor);
		Article article = this.articleService.findById(aid);
		model.addAttribute("article", article);
		makeSidebar(request, model);
		return "article";
	}
}
